import 'package:flutter/material.dart';
import '../app_data_manager.dart';
import '../widges/monthly_line_chart.dart';

class GoalPage extends StatefulWidget {
  const GoalPage({super.key});

  @override
  State<GoalPage> createState() => _GoalPageState();
}

class _GoalPageState extends State<GoalPage> {
  @override
  void initState() {
    super.initState();
    // 确保数据加载后刷新页面
    AppDataManager().init().then((_) {
      if (mounted) setState(() {});
    });
  }

  // 获取所有日期的统计数据
  Map<String, Map<String, int>> _getAllStats() {
    final stats = AppDataManager().goalStats;
    final allStats = <String, Map<String, int>>{};
    
    // 获取当前年份的所有日期
    final currentYear = DateTime.now().year;
    final first = DateTime(currentYear, 1, 1);
    final last = DateTime(currentYear, 12, 31);
    
    for (int i = 0; i <= last.difference(first).inDays; i++) {
      final d = first.add(Duration(days: i));
      final date = '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
      allStats[date] = stats[date] ?? {
        'completed': 0,
        'cancelled': 0,
        'abandoned': 0,
      };
    }
    
    return allStats;
  }

  @override
  Widget build(BuildContext context) {
    final allStats = _getAllStats();
    final String today = '${DateTime.now().year}-${DateTime.now().month.toString().padLeft(2, '0')}-${DateTime.now().day.toString().padLeft(2, '0')}';
    final todayStats = allStats[today] ?? {};
    final todayScore = AppDataManager().getDisciplineScore(today);
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('小目标'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const DisciplineGrid(),
            const SizedBox(height: 16),
            const Text(
              'DDL完成统计',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            Card(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          today,
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Text(
                          '自律值: $todayScore',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: todayScore >= 0 ? Colors.green : Colors.red,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    _buildStatItem(
                      '完成',
                      todayStats['completed'] ?? 0,
                      Colors.green,
                    ),
                    _buildStatItem(
                      '取消',
                      todayStats['cancelled'] ?? 0,
                      Colors.orange,
                    ),
                    _buildStatItem(
                      '放弃',
                      todayStats['abandoned'] ?? 0,
                      Colors.red,
                    ),
                  ],
                ),
              ),
            ),
            const MonthlyLineChart(),
          ],
        ),
      ),
    );
  }

  Widget _buildStatItem(String label, int count, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(
              color: color,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 8),
          Text(
            label,
            style: const TextStyle(fontSize: 16),
          ),
          const Spacer(),
          Text(
            count.toString(),
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  List<String> _getDaysOfYear(int year) {
    final first = DateTime(year, 1, 1);
    final last = DateTime(year, 12, 31);
    List<String> days = [];
    for (int i = 0; i <= last.difference(first).inDays; i++) {
      final d = first.add(Duration(days: i));
      days.add('${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}');
    }
    return days;
  }
}

class DisciplineGrid extends StatefulWidget {
  const DisciplineGrid({super.key});

  @override
  State<DisciplineGrid> createState() => _DisciplineGridState();
}

class _DisciplineGridState extends State<DisciplineGrid> {
  int selectedYear = DateTime.now().year;
  late List<int> years;
  final List<String> weekDays = ['一', '二', '三', '四', '五', '六', '日'];
  final ScrollController _matrixController = ScrollController();
  final ScrollController _monthController = ScrollController();

  @override
  void initState() {
    super.initState();
    years = [for (int y = 2023; y <= DateTime.now().year + 1; y++) y];
    _matrixController.addListener(() {
      if (_monthController.hasClients && _monthController.offset != _matrixController.offset) {
        _monthController.jumpTo(_matrixController.offset);
      }
    });
  }

  @override
  void dispose() {
    _matrixController.dispose();
    _monthController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final days = _getDaysOfYear(selectedYear);
    final weeks = _groupDaysByWeek(days, selectedYear);
    final months = _getMonthsOfYear(selectedYear);
    final monthStartWeek = _getMonthStartWeekIndexes(days, weeks, months);

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      elevation: 4,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.calendar_today, size: 20),
                const SizedBox(width: 8),
                const Text('自律值打卡', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                const Spacer(),
                DropdownButton<int>(
                  value: selectedYear,
                  items: years.map((y) => DropdownMenuItem(value: y, child: Text('$y'))).toList(),
                  onChanged: (y) {
                    if (y != null) {
                      setState(() {
                        selectedYear = y;
                      });
                    }
                  },
                ),
              ],
            ),
            const SizedBox(height: 16),
            // 月份表头（不可滚动，只跟随点阵滚动）
            Row(
              children: [
                const SizedBox(width: 32),
                Expanded(
                  child: SingleChildScrollView(
                    controller: _monthController,
                    scrollDirection: Axis.horizontal,
                    physics: const NeverScrollableScrollPhysics(),
                    child: Row(
                      children: List.generate(weeks.length, (weekIdx) {
                        String? monthLabel;
                        for (int m = 0; m < months.length; m++) {
                          if (monthStartWeek[m] == weekIdx) {
                            monthLabel = '${months[m]}月';
                            break;
                          }
                        }
                        return Container(
                          width: 18,
                          alignment: Alignment.center,
                          child: monthLabel != null ? Text(monthLabel, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold)) : const SizedBox.shrink(),
                        );
                      }),
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 4),
            // 星期表头固定，点阵横向滚动
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 星期表头
                Column(
                  children: List.generate(7, (i) => Container(
                    height: 18,
                    width: 32,
                    alignment: Alignment.centerRight,
                    child: Text('周${weekDays[i]}', style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
                  )),
                ),
                // 点阵
                Expanded(
                  child: SingleChildScrollView(
                    controller: _matrixController,
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: weeks.asMap().entries.map((entry) {
                        final weekIdx = entry.key;
                        final week = entry.value;
                        return Column(
                          children: List.generate(7, (i) {
                            if (i < week.length && week[i] != null) {
                              String date = week[i]!;
                              int score = AppDataManager().getDisciplineScore(date);
                              Color color = _scoreToColor(score);
                              return GestureDetector(
                                onTap: () {
                                  final stats = AppDataManager().goalStats[date] ?? {};
                                  showDialog(
                                    context: context,
                                    builder: (context) => AlertDialog(
                                      title: const Text('自律详情'),
                                      content: SizedBox(
                                        width: double.maxFinite,
                                        child: Column(
                                          mainAxisSize: MainAxisSize.min,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text('日期: $date'),
                                            const SizedBox(height: 8),
                                            Text(
                                              '自律值: $score',
                                              style: TextStyle(
                                                fontSize: 16,
                                                fontWeight: FontWeight.bold,
                                                color: score >= 0 ? Colors.green : Colors.red,
                                              ),
                                            ),
                                            const SizedBox(height: 16),
                                            const Text('完成情况:', style: TextStyle(fontWeight: FontWeight.bold)),
                                            const SizedBox(height: 8),
                                            _buildDetailItem('完成', stats['completed'] ?? 0, Colors.green),
                                            _buildDetailItem('取消', stats['cancelled'] ?? 0, Colors.orange),
                                            _buildDetailItem('放弃', stats['abandoned'] ?? 0, Colors.red),
                                          ],
                                        ),
                                      ),
                                      actions: [
                                        TextButton(
                                          onPressed: () => Navigator.of(context).pop(),
                                          child: const Text('关闭'),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                                child: Container(
                                  margin: const EdgeInsets.all(2),
                                  width: 14,
                                  height: 14,
                                  decoration: BoxDecoration(
                                    color: color,
                                    borderRadius: BorderRadius.circular(3),
                                  ),
                                ),
                              );
                            } else {
                              return Container(
                                margin: const EdgeInsets.all(2),
                                width: 14,
                                height: 14,
                                color: Colors.transparent,
                              );
                            }
                          }),
                        );
                      }).toList(),
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            const Text('绿色=自律，红色=不自律，灰色=无记录', style: TextStyle(fontSize: 12, color: Colors.grey)),
          ],
        ),
      ),
    );
  }

  List<String> _getDaysOfYear(int year) {
    final first = DateTime(year, 1, 1);
    final last = DateTime(year, 12, 31);
    List<String> days = [];
    for (int i = 0; i <= last.difference(first).inDays; i++) {
      final d = first.add(Duration(days: i));
      days.add('${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}');
    }
    return days;
  }

  List<int> _getMonthsOfYear(int year) {
    return List.generate(12, (i) => i + 1);
  }

  List<int> _getMonthStartWeekIndexes(List<String> days, List<List<String?>> weeks, List<int> months) {
    List<int> result = [];
    for (int m = 1; m <= 12; m++) {
      String monthStr = m.toString().padLeft(2, '0');
      for (int w = 0; w < weeks.length; w++) {
        if (weeks[w].any((d) => d != null && d.substring(5, 7) == monthStr)) {
          result.add(w);
          break;
        }
      }
    }
    return result;
  }

  List<List<String?>> _groupDaysByWeek(List<String> days, int year) {
    List<List<String?>> weeks = [];
    List<String?> week = [];

    // 计算1月1日是星期几（1=Monday, 7=Sunday）
    int firstWeekday = DateTime(year, 1, 1).weekday;

    // 补前导空格
    for (int i = 1; i < firstWeekday; i++) {
      week.add(null);
    }

    for (var date in days) {
      week.add(date);
      if (week.length == 7) {
        weeks.add(List.from(week));
        week.clear();
      }
    }
    // 补尾部空格
    if (week.isNotEmpty) {
      while (week.length < 7) {
        week.add(null);
      }
      weeks.add(List.from(week));
    }
    return weeks;
  }

  Color _scoreToColor(int score) {
    if (score == 0) return Colors.grey[300]!;
    if (score > 0) {
      // 绿色，分数越高越深
      int v = (100 + (score * 30)).clamp(100, 255);
      return Color.fromARGB(255, 0, v, 0);
    } else {
      // 红色，分数越低越深
      int v = (100 + (-score * 30)).clamp(100, 255);
      return Color.fromARGB(255, v, 0, 0);
    }
  }

  Widget _buildDetailItem(String label, int count, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Container(
                width: 8,
                height: 8,
                decoration: BoxDecoration(
                  color: color,
                  shape: BoxShape.circle,
                ),
              ),
              const SizedBox(width: 8),
              Text(label),
            ],
          ),
          Text(
            count.toString(),
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }
}